<template>
  <div style="margin-left: 14%">
    <!-- 试品部位配置页 -->
    <el-breadcrumb separator="/">
      <!--面包屑 -->
      <el-breadcrumb-item>
        <i class="el-icon-s-home" style="margin-right: 15px; font-size: 16px"></i>试品部位配置
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="info">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item class="roleInput" label="试品部位">
              <el-input v-model.trim="formInline.productKind" placeholder="请输入试品部位" clearable  size="small"></el-input>
            </el-form-item>
            <el-form-item class="search" label="">
              <el-button size="small" @click="search" style="float: right;" type="primary">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-row>
        <el-button class="addBtn global_add" @click="addProduct" :disabled="btnList.add" style="float:right; margin-right: 15px;margin-bottom: 5px;" type="text">+&nbsp;新增试品部位</el-button>
        </el-row>
        <el-table border stripe :data="productKindList.slice((currentPage-1)*pagesize,currentPage*pagesize)" style="width: 100%">
          <el-table-column align="center" prop="part_name" label="试品部位名称">
          </el-table-column>
          <el-table-column align="center" prop="part_en_name" label="试品部位英文名称">
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button class="global_edit" type="text" @click="editProduct(scope.row)" size="small" :disabled="btnList.edit">编辑</el-button>
              <el-button class="global_edit" type="text" @click="copyProduct(scope.row)" size="small" :disabled="btnList.edit">复制</el-button>
              <el-button class="global_delete" type="text" @click="deleteProduct(scope.row)" style="color: red" size="small" :disabled="btnList.delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
            <el-pagination background :hide-on-single-page="showPagination" :page-size="pagesize" @size-change="currentChange" :current-page.sync='currentPage'
                layout="prev, pager, next"
                :total="productKindList.length">
            </el-pagination>
      </el-card>
    </div>
    <!-- 新增弹出框 -->
    <el-dialog
        title="新增试品部位"
        :visible.sync="dialogVisible"
        width="450px">
        <el-form label-position="right" :rules="addRules" ref="form" :model="form" label-width="120px"  size="small">
            <el-form-item class="mb" label="试品部位" prop="name">
                <el-input v-model.trim="form.name" clearable placeholder="请输入试品部位名称" style="width: 90%"></el-input>
            </el-form-item>
            <el-form-item label="试品部位英文" prop="en_name">
                <el-input v-model.trim="form.en_name" clearable placeholder="请输入试品部位英文名称" style="width: 90%"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button class="textBtn" @click="cancel" size="small">取 消</el-button>
            <el-button type="primary" @click="define" size="small">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog
        title="编辑试品部位"
        :visible.sync="editdialogVisible"
        width="450px">
        <el-form label-position="right" :rules="editRules" ref="editForm" :model="form" label-width="120px" size="small">
            <el-form-item class="mb" label="试品部位" prop="name">
                <el-input v-model.trim="form.name" clearable placeholder="请输入试品部位名称" style="width: 90%"></el-input>
            </el-form-item>
            <el-form-item label="试品部位英文" prop="en_name">
                <el-input v-model.trim="form.en_name" clearable placeholder="请输入试品部位英文名称" style="width: 90%"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button class="textBtn" @click="editCancel" size="small">取 消</el-button>
            <el-button type="primary" @click="editDefine" size="small">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import roleBtn from '../../public/means'
export default {
    data() {
      var validateName = (rule, value, callback) => {
        let reg = /^[\u4e00-\u9fa5（）]{0,}$/
        if(!reg.test(value)){
            callback(new Error('部位名称只能为汉字和中文括号！'));
        }
        callback();
      }
      var validateEnName = (rule, value, callback) => {
        let reg = /^[\u4e00-\u9fa5()]{0,}$/
        if(reg.test(value)){
            callback(new Error('部位英文名称不允许输入汉字！'));
        }
        callback();
      }
      return {
        showPagination: true,
        pagesize:10,
        formInline: {
          productKind: "",
        },
        productKindList: [
        ],
        menu_id: 28,
        uuid:'',
        currentPage: 1,
        roleBtnArr: [],
        btnList: {
          add: false,
          edit: false,
          delete: false
        },
        dialogVisible: false,
        editdialogVisible: false,
        form: {
            name:'',
            en_name: ''
        },
        addRules: {
            name: [
              { required: true, message: '请输入试品部位名称', trigger: 'blur' },
              // { validator: validateName, trigger: 'blur' }
            ],
            en_name: [
              { required: true, message: '请输入试品部位英文名称', trigger: 'blur' },
              { validator: validateEnName, trigger: 'blur' }
            ]
        },
        editRules: {
            name: [
              { required: true, message: '请输入试品部位名称', trigger: 'blur' },
              // { validator: validateName, trigger: 'blur' }
            ],
            en_name: [
              { required: true, message: '请输入试品部位英文名称', trigger: 'blur' },
              { validator: validateEnName, trigger: 'blur' }
            ]
        }
    }
  },
  async created() {
    this.keyupSubmit()
      const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      this.getProductKindList()
      if(role_id){
      // 获取按钮权限状态
      let arr = await roleBtn.roleBtnList(role_id, this.menu_id)
      this.btnList = arr
    }
  },
  methods: {
    keyupSubmit(){
        document.onkeydown=e=>{
          let _key=window.event.keyCode;
          if(_key===13){
            this.search()
          }
        }
      },
      async getProductKindList() {
          const { result } = await this.$http.get('/testProdTemplate/getProdPart?input=')
          this.productKindList = result
      },
      async copyProduct (row) {
        // console.log(555,row);
        const res = await this.$http.post(`/testProdTemplate/copyProdPart`,{ProductData:row})
        if(res.code == 200) {
          this.getProductKindList()
          this.$message.success('复制成功！')
          }
      },
      editProduct(row) {
          this.editdialogVisible = true
          this.form.name = row.part_name
          this.form.en_name = row.part_en_name
          this.uuid = row.part_id
      },
      async deleteProduct(row) {
          const confirm = await this.$confirm('此操作将永久删除该试品部位, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);
        if(confirm !== 'confirm') {
            return this.$message('已取消删除！')
        }
          const res = await this.$http.delete(`/testProdTemplate/deleteProdPart?part_id=${row.part_id}`)
          if(res.code !== 200) {
              return this.$message('删除失败请重试！')
          }
          this.productKindList.splice(this.productKindList.indexOf(row),1)
          this.$message.success('删除成功！')
      },
      currentChange(val) {
          this.pagesize = val
      },
      addProduct(){
          this.dialogVisible = true
      },
      cancel() {
          this.dialogVisible = false
          this.$refs.form.resetFields()
      },
      editCancel() {
          this.editdialogVisible = false
          this.$refs.editForm.resetFields()
          this.form.name = '',
          this.form.en_name = ''
      },
      b(id) {
          let y;
          for(let i = 0; i<this.productKindList.length; i++) {
              if(this.productKindList[i].part_name === this.form.name){
                  if(this.productKindList[i].part_id === id){
                      
                  }else{
                      y = 0
                      break
                  }
              }
              if(this.productKindList[i].part_en_name === this.form.en_name){
                  if(this.productKindList[i].part_id === id){
                      
                  }else{
                      y = 1
                  }
              }
          }
          return y
      },
      async editDefine() {
          const flag = await this.$refs.editForm.validate().catch(err=>err)
          if(!flag) {
              return
          }
          let a = await this.b(this.uuid)
            if(a ===0) {
                return this.$message.error('试品部位名称不能重复！')
            }else if (a === 1) {
                return this.$message.error('试品部位英文名称不能重复！')
            }
          const res = await this.$http.post('/testProdTemplate/setProdPart',{part_id: this.uuid, part_name: this.form.name, part_en_name: this.form.en_name})
          if(res.code !== 200) {
              return this.$message.error('更新失败请重试！')
          }else{
            this.$message.success('更新成功！')
            this.productKindList.forEach(item => {
                if(item.part_id === this.uuid) {
                    item.part_name = this.form.name
                    item.part_en_name = this.form.en_name
                }
            })
          }
          this.form.name = '',
          this.form.en_name = ''
          this.editdialogVisible = false
      },
      a() {
          let x;
          for(let i = 0; i<this.productKindList.length; i++) {
              if(this.productKindList[i].part_name === this.form.name){
                  x = 0
                  break
              }
              if(this.productKindList[i].part_en_name === this.form.en_name){
                  x = 1
              }
          }
          return x
      },
      async define() {
        const flag = await this.$refs.form.validate().catch(err=>err)
        if(!flag) {
            return
        }
        let a = await this.a()
        if(a ===0) {
            return this.$message.error('试品部位名称不能重复！')
        }else if (a === 1) {
            return this.$message.error('试品部位英文名称不能重复！')
        }
        const res = await this.$http.post('/testProdTemplate/setProdPart',{part_name: this.form.name, part_en_name: this.form.en_name}).catch(err=>err)
        if(res.code !== 200) {
            return this.$message.error('新增失败请重试！')
        }else{
            this.form.name = ''
            this.form.en_name = ''
            this.productKindList.splice((this.currentPage-1)*this.pagesize, 0, res.result)
            this.$message.success('新增成功！')
        }
        this.dialogVisible = false
      },
      async search() {
        if(this.formInline.productKind){
          const { result } = await this.$http.get(`/testProdTemplate/getProdPart?input=${this.formInline.productKind}`)
          this.productKindList = result
        }else {
          this.getProductKindList()
        }
      }
  }

}
</script>

<style lang="scss" scoped>
@import "./TestSite.scss";
</style>